package com.travel.common.util;

import com.travel.common.CommonConstant;

import java.io.*;
import java.util.Date;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/4 21:55
 * @Desc:
 */
public class FileUploadUtil {

    /**
     * 上传图片到本地
     * @param inputStream
     * @param filePath
     * @param fileName
     * @return
     */
    public static boolean uploadPic(InputStream inputStream, String filePath, String fileName){
        OutputStream os = null;
        try {
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件

            File tempFile = new File(filePath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return true;
    }

    /**
     * 获取当天文件夹
     * @return
     */
    public static String getDayDir(){
        String month = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDD);
        return month;
    }

    public static String getExcelFileName(String typeName, String userName){
        return typeName + CommonConstant.DOWN_STR + System.currentTimeMillis() + CommonConstant.DASH_STR + userName;
    }

    public static String getPicFileName(){
        return "upload" + CommonConstant.DASH_STR + System.currentTimeMillis();
    }
}
